<template>
    <div class="account-login">
        <a-form
            ref="formRef"
            name="custom-validation"
            :model="formState"
            label-align="right"
            :labelCol="{span: 6, offset: 0}"
            :rules="rules"
        >
            <a-form-item has-feedback label="用户名" name="username" required>
                <a-input v-model:value="formState.username" type="text" autocomplete="off" />
            </a-form-item>
            <a-form-item has-feedback label="密码" name="password" required>
                <a-input-password v-model:value="formState.password" autocomplete="off" />
            </a-form-item>
        </a-form>
    </div>
</template>
<script setup lang="ts">
import cacheFactory,{CacheType} from "@/utils/cache/cache-factory";
import { reactive, ref} from "vue";
import type { FormInstance } from 'ant-design-vue';
import {accountLoginRule} from "@v/login/config/account-login";
import lStore  from "@/store/login/login-store"

interface FormState {
    username: string;
    password: string;
}

let loginStore = lStore()

const formRef = ref<FormInstance>();
const formState = reactive<FormState>({
    password: cacheFactory.instance(CacheType.LOCAL_STORAGE)?.getCache("password") ?? "" ,
    username: cacheFactory.instance(CacheType.LOCAL_STORAGE)?.getCache("username") ?? ""
});

const rules = reactive(accountLoginRule)

const loginHandler = (isKeepPasswprd: boolean) => {
    console.log("账号密码登陆开始～")
    formRef.value?.validate().then(valid => {
        if (!valid){
            Promise.reject("")
        }
        // 1. 判断是否需要记住密码
        if (isKeepPasswprd){
            console.log("记住密码咯～")
            // 本地缓存
            cacheFactory.instance(CacheType.LOCAL_STORAGE)?.setCache("username", formState.username )
            cacheFactory.instance(CacheType.LOCAL_STORAGE)?.setCache("password", formState.password  )
        }else{
            // 本地缓存
            cacheFactory.instance(CacheType.LOCAL_STORAGE)?.remove("username" )
            cacheFactory.instance(CacheType.LOCAL_STORAGE)?.remove("password"  )
        }
        // 2. 开始进行登陆验证
        loginStore.accountLogin({...formState})
    }).catch(error => {
        return false;
    })
}
defineExpose({
    loginHandler
})
</script>

<style scoped lang="less">
.account-login{
    :deep(.ant-form-item-explain-error){
        font-size: 12px;
    }
}
</style>
